package com.srwl.mytx.utils;

import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;

import com.srwl.mytx.MyApplication;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.math.BigDecimal;
import java.nio.channels.FileChannel;

public class FileUtils {
    public static Object readObject(String pathName) {
        InputStream in = readFile(pathName);
        ObjectInputStream ois = null;
        Object obj = null;
        if (in != null) {
            try {
                ois = new ObjectInputStream(in);
                obj = ois.readObject();
            } catch (StreamCorruptedException var26) {
                Log.e("WxException", var26.getMessage(), var26);
            } catch (IOException var27) {
                Log.e("WxException", var27.getMessage(), var27);
            } catch (ClassNotFoundException var28) {
                Log.e("WxException", var28.getMessage(), var28);
            } catch (Exception var29) {
                Log.e("WxException", var29.getMessage(), var29);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                        in = null;
                    } catch (IOException var25) {
                        Log.e("WxException", var25.getMessage(), var25);
                    }
                }

                if (ois != null) {
                    try {
                        ois.close();
                        ois = null;
                    } catch (IOException var24) {
                        Log.e("WxException", var24.getMessage(), var24);
                    }
                }

            }
        }

        return obj;
    }

    public static void writeObject(String path, String name, Object obj) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        File _file = new File(path, name);
        if (_file.exists()) {
            _file.delete();
        }

        try {
            fos = new FileOutputStream(_file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(obj);
            oos.flush();
        } catch (FileNotFoundException var23) {
            Log.e("WxException", var23.getMessage(), var23);
        } catch (IOException var24) {
            Log.e("WxException", var24.getMessage(), var24);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException var22) {
                    Log.e("WxException", var22.getMessage(), var22);
                }
            }

            if (oos != null) {
                try {
                    oos.close();
                    oos = null;
                } catch (IOException var21) {
                    Log.e("WxException", var21.getMessage(), var21);
                }
            }

        }

    }

    public static String getAppPath(Context context) {
        return context.getFilesDir().getAbsolutePath();
    }

    public static InputStream readFile(String pathName) {
        File file = new File(pathName);
        FileInputStream fis = null;
        if (file.exists() && file.isFile()) {
            try {
                fis = new FileInputStream(file);
            } catch (FileNotFoundException var4) {
                Log.e("WxException", var4.getMessage(), var4);
            }
        }

        return fis;
    }

    public static void deleteFile(File file) {
        if (file.exists()) {
            boolean isDirectory = file.isDirectory();
            if (!isDirectory) {
                file.delete();
            } else {
                File[] subFiles = file.listFiles();
                File[] arr$ = subFiles;
                int len$ = subFiles.length;

                for (int i$ = 0; i$ < len$; ++i$) {
                    File subFile = arr$[i$];
                    deleteFile(subFile);
                }

                file.delete();
            }
        }
    }

    public static boolean copyDirectory(File srcDir, File toDir) {
        if (srcDir.exists() && srcDir.isDirectory()) {
            if (!toDir.exists()) {
                toDir.mkdir();
            }

            File[] subFiles = srcDir.listFiles();
            File[] arr$ = subFiles;
            int len$ = subFiles.length;

            for (int i$ = 0; i$ < len$; ++i$) {
                File file = arr$[i$];
                String fileName = file.getName();
                File to = new File(toDir.getAbsoluteFile() + File.separator + fileName);
                if (file.isFile()) {
                    copyFile(file, to);
                } else {
                    copyDirectory(file, to);
                }
            }

            return true;
        } else {
            return false;
        }
    }

    public static void copyFileFast(File in, File out) throws IOException {
        String parent = out.getParent();
        File parentFile = new File(parent);
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        FileChannel inChannel = (new FileInputStream(in)).getChannel();
        FileChannel outChannel = (new FileOutputStream(out)).getChannel();

        try {
            inChannel.transferTo(0L, inChannel.size(), outChannel);
        } catch (IOException var10) {
            throw var10;
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }

            if (outChannel != null) {
                outChannel.close();
            }

        }

    }

    public static boolean copyFile(File from, File to) {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            File dir = new File(to.getParent());
            dir.mkdirs();
            to.createNewFile();
            fis = new FileInputStream(from);
            if (fis == null) {
                return false;
            } else {
                fos = new FileOutputStream(to);
                byte[] buffer = new byte[1024];
                boolean var6 = false;

                int len;
                while ((len = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }

                fos.flush();
                boolean var7 = true;
                return var7;
            }
        } catch (IOException var23) {
            Log.e("WxException", var23.getMessage(), var23);
            return false;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException var22) {
                    Log.e("WxException", var22.getMessage(), var22);
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException var21) {
                    Log.e("WxException", var21.getMessage(), var21);
                }
            }

        }
    }

    public static boolean copyFile(Context context, Uri from, File to) {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            File dir = new File(to.getParent());
            dir.mkdirs();
            to.createNewFile();
            ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(from, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            fis = new FileInputStream(fileDescriptor);
            if (fis == null) {
                return false;
            } else {
                fos = new FileOutputStream(to);
                byte[] buffer = new byte[1024];
                boolean var6 = false;

                int len;
                while ((len = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }

                fos.flush();
                boolean var7 = true;
                return var7;
            }
        } catch (IOException var23) {
            Log.e("WxException", var23.getMessage(), var23);
            return false;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException var22) {
                    Log.e("WxException", var22.getMessage(), var22);
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException var21) {
                    Log.e("WxException", var21.getMessage(), var21);
                }
            }

        }
    }

    public static void writeFile(String path, String name, InputStream inputStream) {
        byte[] bytes = input2Byte(inputStream);
        writeFile(path, name, bytes);
    }

    private static byte[] input2Byte(final InputStream is) {
        if (is == null) return null;
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b, 0, 1024)) != -1) {
                os.write(b, 0, len);
            }
            return os.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void writeFile(String path, String name, byte[] data) {
        if (data != null && data.length > 0) {
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }

            File _file = new File(path, name);
            if (_file.exists()) {
                _file.delete();
            }

            try {
                _file.createNewFile();
            } catch (IOException var20) {
                Log.e("WxException", "failed to create new file");
            }

            FileOutputStream fos = null;

            try {
                fos = new FileOutputStream(_file);
                fos.write(data);
                fos.flush();
            } catch (FileNotFoundException var18) {
                Log.e("WxException", var18.getMessage(), var18);
            } catch (IOException var19) {
                Log.e("WxException", var19.getMessage(), var19);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException var17) {
                        Log.e("WxException", var17.getMessage(), var17);
                    }
                }

            }

        }
    }

    public static String readTextFile(String filePath) {
        String res = "";

        try {
            FileInputStream fin = new FileInputStream(filePath);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];
            boolean var5 = false;

            int size;
            while ((size = fin.read(buffer)) != -1) {
                out.write(buffer, 0, size);
            }

            fin.close();
            byte[] content = out.toByteArray();
            res = new String(content, "UTF-8");
        } catch (Exception var7) {
            Log.w("WXFileTools", "readTextFile filePath:" + filePath, var7);
            res = "";
        }

        return res;
    }

    public static String bytes2KOrM(long bytes) {
        if (bytes == 0L) {
            return "";
        } else {
            BigDecimal filesize = new BigDecimal(bytes);
            BigDecimal megabyte = new BigDecimal(1048576);
            float returnValue = filesize.divide(megabyte, 2, 0).floatValue();
            if (returnValue >= 1.0F) {
                return returnValue + "M";
            } else {
                BigDecimal kilobyte = new BigDecimal(1024);
                returnValue = filesize.divide(kilobyte, 2, 0).floatValue();
                return returnValue + "K";
            }
        }
    }

    public static void nioTransferCopy(File source, File target) {
        FileChannel in = null;
        FileChannel out = null;
        FileInputStream inStream = null;
        FileOutputStream outStream = null;

        try {
            inStream = new FileInputStream(source);
            outStream = new FileOutputStream(target);
            in = inStream.getChannel();
            out = outStream.getChannel();
            in.transferTo(0L, in.size(), out);
        } catch (IOException var15) {
            Log.w("WXFileTools", "nioTransferCopy", var15);
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }

                if (in != null) {
                    in.close();
                }

                if (outStream != null) {
                    outStream.close();
                }

                if (out != null) {
                    out.close();
                }
            } catch (IOException var14) {
                Log.w("WXFileTools", "nioTransferCopy", var14);
            }

        }

    }

    public static void copyDataBaseToDirImpl(Context context, String dbName, String destDir) {
        if (context != null && !TextUtils.isEmpty(dbName)) {
            File srcFile = new File(context.getFilesDir().getParentFile().getPath() + "/databases/" + dbName);
            if (!srcFile.exists()) {
                Log.d("WXFileTools", "copyDataBaseToSdcardImpl not exist fileName=" + srcFile.getAbsolutePath());
            } else {
                Log.d("WXFileTools", "starting copy DB...");
                File targetPath = new File(destDir);
                if (!targetPath.exists()) {
                    targetPath.mkdirs();
                }

                File targetFile = new File(targetPath.getAbsolutePath(), dbName);
                if (targetFile.exists()) {
                    targetFile.delete();
                }

                nioTransferCopy(srcFile, targetFile);
                Log.d("WXFileTools", "copy over dir=" + targetFile.getAbsolutePath());
            }
        }
    }

    public static boolean isSdCardAvailable() {
        boolean isAvailable = true;
        Context context = MyApplication.getInstance();
        if (Build.VERSION.SDK_INT >= 23 && context != null) {
            PackageManager pm = context.getPackageManager();
            int sdCardPermission = pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", context.getPackageName());
            isAvailable = sdCardPermission == 0;
        }

        if (isAvailable) {
            try {
                if (!"mounted".equals(Environment.getExternalStorageState())) {
                    isAvailable = false;
                }
            } catch (NullPointerException var4) {
                isAvailable = false;
            }
        }

        return isAvailable;
    }

    public static long getSDFreeSize() {
        String sdcard = Environment.getExternalStorageState();
        if (sdcard.equals(Environment.MEDIA_MOUNTED)) {
            File file = Environment.getExternalStorageDirectory();
            StatFs statFs = new StatFs(file.getPath());
            //获得Sdcard上每个block的size
            long blockSize = statFs.getBlockSizeLong();
            //获取可供程序使用的Block数量
            long blockavailable = statFs.getAvailableBlocksLong();
            //计算标准大小使用：1024，当然使用1000也可以
            long blockavailableTotal = blockSize * blockavailable / 1000 / 1000;
            return blockavailableTotal;
        } else {
            return -1;
        }

    }
}
